import {
    createSlice
} from "@reduxjs/toolkit";
import {useSelector} from "react-redux";
import {getHospitalSet, getHospitalSetLockId} from "@/api/hosp";

const hospSlice = createSlice({
    name:"hosp",
    initialState:{
        hospSetList:[]
    },
    reducers:{
        upHospSetList(state,{payload}){
            state.hospSetList = payload;
        },
        changeStateById(state,{payload}){
            const info:any = state.hospSetList.find((v:any)=>v.id === payload);
            info.status = info.status===0?1:0;
        }
    }
})
export const {upHospSetList,changeStateById} = hospSlice.actions;
// 获取状态列表
export const getHospitalSetAsync = function(page:number,limit:number){
    return async (dispatch:any)=>{
        const result = await getHospitalSet(page,limit);
        dispatch(upHospSetList(result.data.records));
    }
}
// 完成锁定2:更新服务端的锁定状态，然后重新获取当前页的信息，进行渲染
// 优点：可以将最后操作以后的最新数据进行呈现
export const getHospitalSetLockIdAsync = function(id:number,status:number){
    return async (dispatch:any)=>{
        await getHospitalSetLockId(id,status);
        dispatch(getHospitalSetAsync(1,5));
    }
}
// 完成锁定1： 优点：减少ajax请求
// export const getHospitalSetLockIdAsync = function(id:number,status:number){
//     return async (dispatch:any)=>{
//         await getHospitalSetLockId(id,status);
//         dispatch(changeStateById(id));
//     }
// }
// 导出状态
export const useSelectorHosp = ()=>useSelector((state:any)=>state.hosp);
export default hospSlice.reducer;